﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;

namespace Install_SimpleBackup
{
    public partial class InstallForm : Form
    {
        public InstallForm()
        {
            InitializeComponent();
            txtDirProg.Text = "C:\\Program Files\\SimpleBackup";
            txtDirBackup.Text = "C:\\Backup";
            ChooseDirProg.SelectedPath = txtDirProg.Text;
            ChooseDirBackup.SelectedPath = txtDirBackup.Text;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            CloseForm();
        }

        private void CloseForm()
        {
            this.Close();
            this.Dispose();
        }

        private void btnDirBackup_Click(object sender, EventArgs e)
        {
            if (ChooseDirBackup.ShowDialog() == DialogResult.OK)
                txtDirBackup.Text = ChooseDirBackup.SelectedPath;
        }

        private void btnDirProg_Click(object sender, EventArgs e)
        {
            if (ChooseDirProg.ShowDialog() == DialogResult.OK)
                txtDirProg.Text = ChooseDirProg.SelectedPath;
        }

        private void btnInstall_Click(object sender, EventArgs e)
        {
            bool bContinue;

            // 1 - Check Program Directory
            bContinue = ManageDirProg();
            if (!bContinue)
                return ;

            // 2 - Check Backup Directory
            bContinue = ManageDirBackup();
            if (!bContinue)
                return ;

            // 3 - Write script Files
            String sFileName1 = txtDirProg.Text + "\\" + SimpleBackup.sCopyFileName;
            String sContent1 = SimpleBackup.sCopyFile.Replace("__DIR_BACKUP__", txtDirBackup.Text + "\\");
            bContinue = WriteFile(sFileName1, sContent1);
            if (!bContinue)
                return ;

            String sFileName2 = txtDirProg.Text + "\\" + SimpleBackup.sCopyDirName;
            String sContent2 = SimpleBackup.sCopyDir.Replace("__DIR_BACKUP__", txtDirBackup.Text + "\\");
            bContinue = WriteFile(sFileName2, sContent2);
            if (!bContinue)
                return;

            // 4 - Create Registry Entry
            bContinue = WriteRegistryCopyFile(sFileName1);
            if (!bContinue)
                return;

            bContinue = WriteRegistryCopyDir(sFileName2);
            if (!bContinue)
                return;

            // 5 - Write Uninstall Files
            String sFileNameReg =  txtDirProg.Text + "\\Uninstall.reg";
            String sContentReg = "Windows Registry Editor Version 5.00\r\n[-HKEY_CLASSES_ROOT\\*\\shell\\SimpleBackup]\r\n[-HKEY_CLASSES_ROOT\\Folder\\shell\\SimpleBackup]";
            bContinue = WriteFile(sFileNameReg, sContentReg);
            if (!bContinue)
                return;

            String sFileNameBat = txtDirProg.Text + "\\Uninstall.bat";
            String sContentBat = "@regedit /s Uninstall.reg";
            bContinue = WriteFile(sFileNameBat, sContentBat);
            if (!bContinue)
                return;

            MessageBox.Show("Installation succeeded", "Success");
            this.Close();
        }

        private bool WriteRegistryCopyFile(String sFileName)
        {
            try
            {
                RegistryKey rKey = Registry.ClassesRoot;
                rKey = rKey.CreateSubKey("*\\shell\\SimpleBackup\\command");
                rKey.SetValue("", sFileName + " \"%1\"");
                return true;
            }
            catch (Exception)
            {
                MessageBox.Show("Error : Failed to create registry entry.\r\nPlease check that you have sufficient privileges.", "Fail to write registry", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
            return false;
        }

        private bool WriteRegistryCopyDir(String sFileName)
        {
            try
            {
                RegistryKey rKey = Registry.ClassesRoot;
                rKey = rKey.CreateSubKey("Folder\\shell\\SimpleBackup\\command");
                rKey.SetValue("", sFileName + " \"%1\"");
                return true;
            }
            catch (Exception)
            {
                MessageBox.Show("Error : Failed to create registry entry.\r\nPlease check that you have sufficient privileges.", "Fail to write registry", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
            return false;
        }

        private bool WriteFile(String sFileName, String sContent)
        {
            try
            {
                StreamWriter fBackupFile = new StreamWriter(sFileName, false);
                fBackupFile.Write(sContent);
                fBackupFile.Close();
                if (File.Exists(sFileName))
                    return true;
                else
                    throw new Exception();
            }
            catch (Exception)
            {
                MessageBox.Show("Error : Failed to create file " + sFileName + "\r\nPlease check that you have sufficient privileges.", "Fail to write file", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
            return false;
        }

        /*
         * Create the folder if it doesn't exist.
         */
        private bool ManageDirProg()
        {
            bool bResult;
            String sDir = txtDirProg.Text;

            if (!FolderExists(sDir))
            {
                bResult = CreateFolder(sDir);
                if (bResult == false)
                    MessageBox.Show("Error : Failed to create folder " + sDir + "\r\nPlease check that you have sufficient privileges.", "Error");
            }
            else
            {
                String sTitle = "Existing Folder";
                String sQuestion = "The folder " + sDir + " already exists. Do you still want to use it ?";
                bResult = MessageBox.Show(sQuestion, sTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes;
            }
            return bResult;
        }

        private bool ManageDirBackup()
        {
            bool bResult;
            String sDir = txtDirBackup.Text;

            if (!FolderExists(sDir))
            {
                bResult = CreateFolder(sDir);
                if (bResult == false)
                    MessageBox.Show("Error : Failed to create folder " + sDir + "\r\nPlease check that you have sufficient privileges.", "Error");
            }
            else
                bResult = true;
            return bResult;
        }

        private bool CreateFolder(String sDir)
        {
            try
            {
                DirectoryInfo di = new DirectoryInfo(sDir);
                di.Create();
                di.Refresh();
                return di.Exists;
            }
            catch (Exception)
            { }
            return false;
        }

        private bool FolderExists(String sDir)
        {
            try
            {
                DirectoryInfo di = new DirectoryInfo(sDir);
                return di.Exists;
            }
            catch (Exception)
            { }
            return false;
        }
    }
}
